<template>
  <div class="alarm-table-container h-full flex flex-col">
    <!-- 表格头部 -->
    <div class="table-header border-b border-#0efcff/30">
      <div class="table-row px-4 py-3">
        <div class="table-grid">
          <div class="col-pool font-bold">水池名称</div>
          <div class="col-device font-bold">设备名称</div>
          <div class="col-reason font-bold">报警原因</div>
          <div class="col-time font-bold">报警时间</div>
        </div>
      </div>
    </div>

    <!-- 表格内容 -->
    <div class="table-body flex-1 overflow-hidden">
      <div
        class="table-content"
        :style="{ transform: `translateY(-${currentOffset}px)` }"
      >
        <div
          v-for="(item, index) in displayData"
          :key="`${index}-${item.poolName}-${item.time}`"
          class="table-row border-b border-#0efcff/10 px-4 py-3 transition-colors hover:bg-#0efcff/5"
          :class="{ 'bg-#0efcff/3': index % 2 === 0 }"
        >
          <div class="table-grid">
            <div class="col-pool truncate">
              {{ item.poolName }}
            </div>
            <div class="col-device">{{ item.deviceName }}</div>
            <div class="col-reason alarm-reason-text font-bold">
              {{ item.reason }}
            </div>
            <div class="col-time text-#0efcff">
              {{ item.time }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from "vue";

interface AlarmItem {
  poolName: string;
  deviceName: string;
  reason: string;
  time: string;
  level: "high" | "medium" | "low"; // 报警级别
}

// 接收外部传入的报警数据
const props = defineProps<{
  alarmData?: AlarmItem[];
}>();

// 使用传入的数据或默认数据
const alarmData = computed(() => {
  return props.alarmData && props.alarmData.length > 0
    ? props.alarmData
    : [
        {
          poolName: "暂无报警",
          deviceName: "-",
          reason: "系统正常",
          time: new Date().toLocaleString("zh-CN"),
          level: "low" as const,
        },
      ];
});

const currentOffset = ref(0);
const rowHeight = 52; // 每行的高度（包括padding和border）
const containerHeight = ref(0);
const visibleRows = ref(0);
const scrollSpeed = ref(0.5); // 每次滚动的像素数，控制滚动速度
let animationId: number | null = null;

// 计算可见行数
const calculateVisibleRows = () => {
  const container = document.querySelector(".table-body");
  if (container) {
    containerHeight.value = container.clientHeight;
    visibleRows.value = Math.floor(containerHeight.value / rowHeight);
  }
};

// 判断是否需要滚动
const needsScrolling = computed(() => {
  return alarmData.value.length > visibleRows.value;
});

// 创建循环数据用于无缝滚动
const displayData = computed(() => {
  const data = alarmData.value;
  // 如果不需要滚动，直接返回原数据
  if (!needsScrolling.value) {
    return data;
  }
  // 需要滚动时，复制数据以实现无缝循环
  return [...data, ...data];
});

// 自动滚动函数
const autoScroll = () => {
  if (visibleRows.value === 0) {
    animationId = requestAnimationFrame(autoScroll);
    return;
  }

  // 如果不需要滚动，停止动画
  if (!needsScrolling.value) {
    currentOffset.value = 0;
    return;
  }

  // 计算一个完整数据集的高度
  const singleSetHeight = alarmData.value.length * rowHeight;

  // 平滑滚动
  currentOffset.value += scrollSpeed.value;

  // 当滚动超过一个完整数据集时，重置到开始位置
  if (currentOffset.value >= singleSetHeight) {
    currentOffset.value = 0;
  }

  // 继续下一帧动画
  animationId = requestAnimationFrame(autoScroll);
};

// 启动或停止滚动动画
const startScrolling = () => {
  if (animationId) {
    cancelAnimationFrame(animationId);
    animationId = null;
  }

  if (needsScrolling.value) {
    animationId = requestAnimationFrame(autoScroll);
  } else {
    currentOffset.value = 0;
  }
};

onMounted(() => {
  // 延迟计算，确保DOM已渲染
  setTimeout(() => {
    calculateVisibleRows();
    // 根据是否需要滚动来决定是否启动动画
    startScrolling();
  }, 100);

  // 监听窗口大小变化
  window.addEventListener("resize", () => {
    calculateVisibleRows();
    startScrolling();
  });
});

// 监听报警数据变化，重新判断是否需要滚动
watch(
  () => alarmData.value,
  () => {
    setTimeout(() => {
      startScrolling();
    }, 50);
  },
  { deep: true }
);

onUnmounted(() => {
  if (animationId) {
    cancelAnimationFrame(animationId);
  }
  window.removeEventListener("resize", calculateVisibleRows);
});
</script>

<style scoped>
.alarm-table-container {
  font-size: 13px;
  color: #0efcff;
}

.table-row {
  min-height: 52px;
  display: flex;
  align-items: center;
}

.table-header {
  background: rgba(14, 252, 255, 0.15);
  backdrop-filter: blur(5px);
  border-radius: 4px 4px 0 0;
  text-shadow: 0 0 8px rgba(14, 252, 255, 0.6);
}

.table-header .table-row {
  background: transparent;
}

.table-row:hover {
  background: rgba(14, 252, 255, 0.08) !important;
  box-shadow: inset 0 0 20px rgba(14, 252, 255, 0.1);
}

/* 表格网格布局 */
.table-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1.5fr 1fr;
  gap: 1rem;
  align-items: center;
  width: 100%;
}

.col-pool,
.col-device,
.col-reason,
.col-time {
  text-align: center;
  justify-self: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 发光效果 */
.table-header div {
  text-shadow: 0 0 12px rgba(102, 204, 255, 0.9);
}

/* 报警原因高亮 */
.alarm-reason-text {
  color: #f48fb1 !important;
  text-shadow: 0 0 10px rgba(244, 143, 177, 0.7);
  animation: alarmBlink 2s infinite;
}

@keyframes alarmBlink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

/* 时间文字发光 */
.text-#0efcff {
  text-shadow: 0 0 10px rgba(102, 204, 255, 0.7);
}
</style>
